package com.qiaofang.applet.rest;

import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.dto.PageDataRequest;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.service.member.domain.Department;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.domain.MemberOperate;
import com.qiaofang.applet.service.member.repository.DepartmentRepository;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.MemberBrowseService;
import com.qiaofang.applet.service.member.service.MemberExploreService;
import com.qiaofang.applet.service.member.service.MemberService;
import com.qiaofang.applet.service.member.service.dto.EmployeeListDto;
import com.qiaofang.applet.service.member.service.dto.MemberExploreAddDto;
import com.qiaofang.applet.service.member.service.dto.MemberOperateQueryDto;
import com.qiaofang.applet.service.member.service.mapstruct.EmployeeMapper;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.applet.service.property.service.dto.*;
import com.qiaofang.applet.service.property.service.mapstruct.FirsthandEstateMapper;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author daiyuxaing
 */
@Slf4j
@RestController
@RequestMapping("/api/pcweb/auth/memberBrowse")
@Api(tags = "会员：会员浏览记录")
public class MemberExploreController {

    @Autowired
    MemberService membeService;

    @Autowired
    MemberBrowseService memberBrowseService;

    @Autowired
    private MemberExploreService memberExploreService;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private FirsthandEstateMapper firsthandEstateMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentRepository departmentRepository;

    @PostMapping("/searchFirsthandEstateBrowse")
    @ApiOperation(value = "查询新房浏览记录列表", notes = "查询新房浏览记录列表")
    public DataResponse<Page<FirsthandEstateListDto>> searchFirsthandEstateBrowse(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<FirsthandEstateListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberOperateQueryDto memberOperateQueryDto = new MemberOperateQueryDto();
        memberOperateQueryDto.setMemberId(request.getParam().getId());
        memberOperateQueryDto.setBusinessType(BusinessConstants.FIRSTHAND_ESTATE.getCode());
        Page<MemberOperate> page = memberExploreService.getExploreRecords(memberOperateQueryDto, pageable);

        if (page.getTotalElements() > 0) {
            List<String> uuidList = page.stream().map(MemberOperate::getBusinessUuid).collect(Collectors.toList());

            FirsthandEstateQueryDto queryDto = new FirsthandEstateQueryDto();
            queryDto.setEstateUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            List<FirsthandEstate> propertyList = firsthandEstateService.findAllByParams(queryDto);

            Map<String, FirsthandEstateListDto> propertyMap = propertyList.stream()
                    .collect(Collectors.toMap(FirsthandEstate::getEstateUniqueUuid, firsthandEstateMapper::domainToListDto, (a1, a2) -> a2));
            result = new PageImpl<>(uuidList.stream().map(propertyMap::get).collect(Collectors.toList()), pageable, page.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchSaleBrowse")
    @ApiOperation(value = "查询二手房浏览记录列表", notes = "查询二手房浏览记录列表")
    public DataResponse<Page<SalePropertyListDto>> searchSaleBrowse(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<SalePropertyListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberOperateQueryDto memberOperateQueryDto = new MemberOperateQueryDto();
        memberOperateQueryDto.setMemberId(request.getParam().getId());
        memberOperateQueryDto.setBusinessType(BusinessConstants.SALE_PROPERTY.getCode());
        Page<MemberOperate> page = memberExploreService.getExploreRecords(memberOperateQueryDto, pageable);

        if (page.getTotalElements() > 0) {
            List<String> uuidList = page.stream().map(MemberOperate::getBusinessUuid).collect(Collectors.toList());

            SalePropertyQueryDto queryDto = new SalePropertyQueryDto();
            queryDto.setPropertyUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            List<Property> propertyList = propertyService.findAllSaleByParams(queryDto);

            Map<String, SalePropertyListDto> propertyMap = propertyList.stream()
                    .collect(Collectors.toMap(Property::getPropertyUniqueUuid, propertyMapper::domainToSaleListDto, (a1, a2) -> a2));
            result = new PageImpl<>(uuidList.stream().map(propertyMap::get).collect(Collectors.toList()), pageable, page.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchRentBrowse")
    @ApiOperation(value = "查询租房浏览记录列表", notes = "查询租房浏览记录列表")
    public DataResponse<Page<RentPropertyListDto>> searchRentBrowse(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<RentPropertyListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberOperateQueryDto memberOperateQueryDto = new MemberOperateQueryDto();
        memberOperateQueryDto.setMemberId(request.getParam().getId());
        memberOperateQueryDto.setBusinessType(BusinessConstants.RENT_PROPERTY.getCode());
        Page<MemberOperate> page = memberExploreService.getExploreRecords(memberOperateQueryDto, pageable);

        if (page.getTotalElements() > 0) {
            List<String> uuidList = page.stream().map(MemberOperate::getBusinessUuid).collect(Collectors.toList());

            RentPropertyQueryDto queryDto = new RentPropertyQueryDto();
            queryDto.setPropertyUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            List<Property> propertyList = propertyService.findAllRentByParams(queryDto);

            Map<String, RentPropertyListDto> propertyMap = propertyList.stream()
                    .collect(Collectors.toMap(Property::getPropertyUniqueUuid, propertyMapper::domainToRentListDto, (a1, a2) -> a2));
            result = new PageImpl<>(uuidList.stream().map(propertyMap::get).collect(Collectors.toList()), pageable, page.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchEmployeeBrowse")
    @ApiOperation(value = "查询经纪人浏览记录列表", notes = "查询经纪人浏览记录列表")
    public DataResponse<Page<EmployeeListDto>> searchEmployeeBrowse(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<EmployeeListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberOperateQueryDto memberOperateQueryDto = new MemberOperateQueryDto();
        memberOperateQueryDto.setMemberId(request.getParam().getId());
        memberOperateQueryDto.setBusinessType(BusinessConstants.EMPLOYEE.getCode());
        Page<MemberOperate> page = memberExploreService.getExploreRecords(memberOperateQueryDto, pageable);

        if (page.getTotalElements() > 0) {
            List<String> uuidList = page.stream().map(MemberOperate::getBusinessUuid).collect(Collectors.toList());

            List<Employee> employeeList = employeeService.findAllByEmployeeUuidIn(QfContextHolder.getContext().getCorporationCode(), uuidList);
            //设置部门名称
            List<String> deptUuids = employeeList.stream().map(Employee::getDeptUuid).distinct().collect(Collectors.toList());
            List<Department> departmentList = departmentRepository.findListByDeptUuidInAndCorporationCode(deptUuids, QfContextHolder.getContext().getCorporationCode());
            if (!CollectionUtils.isEmpty(departmentList)) {
                for (Employee employee : employeeList) {
                    for (Department department : departmentList) {
                        if (StringUtils.equals(department.getDeptUuid(), employee.getDeptUuid())) {
                            employee.setDeptName(department.getDeptName());
                        }
                    }
                }
            }
            Map<String, EmployeeListDto> employeeListDtoMap = employeeList.stream()
                    .collect(Collectors.toMap(Employee::getEmployeeUniqueUuid, employeeMapper::domainToDto, (k1, k2) -> k2));

            result = new PageImpl<>(uuidList.stream().map(employeeListDtoMap::get).collect(Collectors.toList()), pageable, page.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加浏览记录", notes = "添加浏览记录")
    public DataResponse<Object> add(@RequestBody @Valid DataRequest<MemberExploreAddDto> request) {
        request.getParam().setCityCode(QfContextHolder.getContext().getCityCode());
        request.getParam().setCityName(QfContextHolder.getContext().getCityName());
        return DataResponse.ok(memberExploreService.addExploreRecord(request.getParam()));
    }


}
